package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ReadBehaviorDto;
import com.heima.behavior.pojos.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocal;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Resource
    MongoTemplate mongoTemplate;
    /**
     * 阅读行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1.参数判断
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.获取用户id
        ApUser apUser = ApThreadLocal.getApUser();
        //表示未登录
        if(apUser==null){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行以下操作
        if(apUser.getId()==0){
            return ResponseResult.okResult(405,"游客身份禁止，需进行登录");
        }
        //3.判断当前mongo中是否已经包含了该数据，如果包含则更新count次数，如果没有包含则直接新增
        ApReadBehavior apReadBehavior = mongoTemplate.findOne(Query.query(
                Criteria.where("userId").is(apUser.getId())
                        .and("articleId").is(dto.getArticleId())
                )
                , ApReadBehavior.class);
        if(apReadBehavior!=null){//说明已经存在该数据，则更新count次数
            apReadBehavior.setCount(apReadBehavior.getCount()+1);
            apReadBehavior.setUpdatedTime(new Date());
            mongoTemplate.save(apReadBehavior);
        }else{
            //说明mongo中还没有数据，则直接新增
            apReadBehavior=new ApReadBehavior();
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setUpdatedTime(new Date());
            apReadBehavior.setUserId(apUser.getId().longValue());
            apReadBehavior.setCount(dto.getCount().intValue());
            mongoTemplate.insert(apReadBehavior);
        }
        return ResponseResult.okResult("阅读完成");
    }
}
